<?php
/**
 * CreateTime: 2023/11/24 15:17
 * User:LinQ
 */

namespace App\Http\Service\Department;

use App\Facade\UserFuncFacade;
use App\Func\System\OperateLogFunc;
use App\Http\Service\BasicInterfaceService;
use App\Models\CompanyDepartment\DepartmentModel;
use App\State\StatusState;


class DepartmentService implements BasicInterfaceService
{
    public function getList(array $prams)
    {
        $page_size = $prams['page_size'] ?? 10;
        $filters = $prams['filters'] ?? [];
        $desc = $prams['desc'] ?? [];
        $departmentModel = new DepartmentModel();
        $this->listSelectDefaultFilters($departmentModel);
        if($filters){
            $this->listSelectFilters($departmentModel,$filters);
        }
        $res = $departmentModel->cListHasCom($departmentModel,$page_size,$desc,[
            '*',
            'responsible_user_id as responsible_user_str',
            'owner_id as owner_str'
        ]);
        // 处理数据
        $res['data'] = $this->dispose($res['data']);
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.department')
        ]));
    }

    public function getSelectHasPage($prams)
    {
        $page_size = $prams['page_size'] ?? 10;
        $filters = $prams['filters'] ?? [];
        $desc = $prams['desc'] ?? [];
        $departmentModel = (new DepartmentModel());
        $this->listSelectDefaultFilters($departmentModel);
        if($filters){
            $this->listSelectFilters($departmentModel,$filters);
        }
        $res = $departmentModel->cListHasCom($departmentModel,$page_size,$desc,[
            'department_name as value'
        ]);
        // 处理数据
        $res['data'] = $this->dispose($res['data']);
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.department')
        ]));
    }

    public function listSelectDefaultFilters($query){
        $query->pushFilter('status',1);
    }

    public function listSelectFilters($query, $filters)
    {
        $filters = trim_array($filters);
        if(map_has_value($filters,'com_id')){
            $query->pushFilter('com_id',$filters['com_id']);
        }
        if(map_has_value($filters,'department_name')){
            $query->pushFilter('department_name',$filters['department_name'],'like');
        }
        if(map_has_value($filters,'department_code')){
            $query->pushFilter('department_code',$filters['department_code'],'like');
        }
    }

    public function getSelect()
    {
        $departmentModel = new DepartmentModel();
        $res = $departmentModel->scopeAddComIdWhere()->select([
            'department_id as key',
            'department_name as value'
        ])->where('status',1)->get();
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.department')
        ]));
    }

    public function getInfo($id)
    {
        $departmentModel = new DepartmentModel();
        $departmentModel->makeVisible('quick_sub_department');

        $res = $departmentModel->select([
            "*",
            "owner_id as owner_str",
            "responsible_user_id as responsible_user_str"
        ])->scopeAddComIdWhere()->where('department_id',$id)->first();

        // 获取下级部门
        $subDepartmentList = $departmentModel->select([
            "department_id",
        ])->where(function ($query) use ($res){
            $query->orWhere('quick_sub_department','like',''.$res->department_id.'.%');
            $query->orWhere('quick_sub_department','like','%.'.$res->department_id.'.%');
        })->get();
        $departmentModel->makeHidden('quick_sub_department');
        $res['sub_list'] = $subDepartmentList;
        s_c_return($res,trans('message.get_detail_ok',[
            'name' => trans('key.department')
        ]));
    }

    public function create($data)
    {
        $departmentModel = new DepartmentModel();
        $userInfo =  UserFuncFacade::getLoginInfo();
        // 设置默认数据
        $insertData = [
            'department_name' => $data['department_name'],
            'responsible_user_id' => $data['responsible_user_id'],
            'pid' => $data['pid'] ?? 0,
            'owner_id' => $userInfo['user_id'],
            'com_id' => $userInfo['com_id'],
            'created_at' => date("Y-m-d h:i:s"),
            'updated_at' => date("Y-m-d h:i:s"),
        ];
        //  快速筛选下级部门预留字段 处理
        if(isset($data['pid'])){
            $pDepartmentInfo = $departmentModel->select(['quick_sub_department'])->find($data['pid']);
            if(!$pDepartmentInfo){
                $insertData['quick_sub_department'] = $data['pid'].".";
            }else{
                $insertData['quick_sub_department'] = $pDepartmentInfo['quick_sub_department'].$data['pid'].".";
            }
        }
        $res = $departmentModel->insertGetId($insertData);
        // 添加操作记录
        OperateLogFunc::addOperate(
            'DepartmentService',$res,'create');

        s_c_return(['department_id'=>$res],trans('message.created_ok',[
            'name' => trans('key.department')
        ]));
    }

    public function fakeDelete($id)
    {
        $departmentModel = new DepartmentModel();
        // 判断当前部门是否存在自己部门 如果存在不允许编辑
        // 获取下级部门
        $subDepartmentList = $departmentModel->select([
            "department_id",
        ])->where(function ($query) use ($id){
            $query->orWhere('quick_sub_department','like',''.$id.'.%');
            $query->orWhere('quick_sub_department','like','%.'.$id.'.%');
        })->get();
        if($subDepartmentList->toArray()){
            s_fail_return(null,trans('message.has_sub_department').trans('message.fake_del_ok',[
                    'name' => trans('key.department')
                ]));
        }
        // 通过状态机修改状态
        $res = (new StatusState())->stateChange($id,
            StatusState::OK_STATUS,
            StatusState::DELETE_STATUS,
            $departmentModel,
            'department_id'
        );
        if(!$res){
            s_fail_return(null,trans('message.fake_del_ok',[
                'name' => trans('key.department')
            ]));
        }
        s_c_return(null,trans('message.fake_del_ok',[
            'name' => trans('key.department')
        ]));
    }

    public function delete($data)
    {

    }

    public function update($data)
    {
        $department_id = $data['department_id'] ?? 0;
        $departmentModel = new DepartmentModel();
        if(isset($data['pid'])){
            // 判断当前部门是否存在自己部门 如果存在不允许编辑
            $subDepartmentList = $departmentModel->select([
                "department_id"
            ])->where(function ($query) use ($department_id){
                $query->whereOr('quick_sub_department',''.$department_id.'.');
                $query->whereOr('quick_sub_department','.'.$department_id.'.');
            })->get();

            if($subDepartmentList){
                s_fail_return(null,trans('message.remove_department_pid'));
            }

            // 判断要移动的部门是否本身属于当前部门的下级部门 如果存在则不允许移动
            $pDepartmentInfo = $departmentModel->select(['quick_sub_department'])->find($data['pid']);
            if($pDepartmentInfo){
                $hasSub = in_array($department_id,explode('.',$pDepartmentInfo->quick_sub_department));
                if($hasSub){
                    s_fail_return(null,trans('message.remove_department_pid_but_is_sub'));
                }
            }

            if(!$pDepartmentInfo){
                $data['quick_sub_department'] = $data['pid'].".";
            }else{
                $data['quick_sub_department'] = $pDepartmentInfo['quick_sub_department'].$data['pid'].".";
            }
        }
        try {
            $res = $departmentModel->where('department_id',$department_id)->update($data);
            if($res){
                // 添加操作记录
                OperateLogFunc::addOperate(
                    'departmentService',$res,'update'
                );
                s_c_return(null,trans('message.update_ok',[
                    'name' => trans('key.department')
                ]));
            }
            s_c_return(null,trans('message.update_err',[
                'name' => trans('key.department')
            ]));
        }catch (\Exception $exception){
            s_c_return(null,trans('message.update_err',[
                'name' => trans('key.department')
            ]));
        }

    }

    public function dispose($data): mixed
    {
        return $data;
    }

    public function fakeDeleteByIds($ids)
    {

    }
}
